package com.fzrskj.cloud.free.sys.dao;

import com.fzrskj.cloud.free.core.tool.CObjectTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.CloudDbDrvUtils;
import com.fzrskj.cloud.free.sys.bean.SysArticle;
import com.fzrskj.cloud.free.sys.bean.SysArticleView;
import ms.core.consts.SysErr;
import ms.core.db.IDbDrv;
import ms.core.object.CObject;
import ms.core.tool.StrTool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wangxinhao
 * @version 2016-10-11
 */
public class SysArticleDao extends CObject {
    //private declarations
    private IDbDrv db = null;

    //constructor function to initialize database access object
    public SysArticleDao() {
        db = CloudDbDrvUtils.getDbUtilsDrv();
    }

    //to free resource
    @Override
    public void dispose() {
        db.closeConnection();
    }

    //to add new record to database by bean
    public int addSysArticle(SysArticle obj) {
        //代理商数据隔离
        obj.setAgentId(CloudContextUtils.getAgentId());

        String sql = "insert into sys_article(title,content,attachmentUrl,publishTime,authorId," +
                "authorName,visitors,showIndex,state,typeId," +
                "parentId,flag,agentId)" +
                " values (?,?,?,?,?," +
                "?,?,?,?,?," +
                "?,?,?)";
        Object[] prm = {obj.getTitle(), obj.getContent(), obj.getAttachmentUrl(), obj.getPublishTime(), obj.getAuthorId(),
                obj.getAuthorName(), obj.getVisitors(), obj.getShowIndex(), obj.getState(), obj.getTypeId(),
                obj.getParentId(), obj.getFlag(), obj.getAgentId()};
        int ret = db.executeSql(sql, prm);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to add new record to database by map
    public int addSysArticle(Map<String, Object> values) {
        //代理商数据隔离
        values.put("agentId", CloudContextUtils.getAgentId());

        int ret = db.insertRecord("sys_article", values);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to delete table record by id
    public int delSysArticle(int id) {
        String sql = "delete from sys_article where id=?";

        Object[] params = {id};
        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        int ret = db.executeSql(sql, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to modify table record by values and condition
    public int modSysArticle(Map<String, Object> values, Map<String, Object> cdt) {
        //代理商数据隔离
        cdt.put("agentId", CloudContextUtils.getAgentId());

        int ret = db.modifyRecord("sys_article", values, cdt);
        String code = db.getErrCode();
        this.setErrCode(code);
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        return ret;
    }

    //to query sys_article item for detail
    public SysArticle querySysArticle(int id) {
        String sql = "select * from sys_article where id=?";

        Object[] params = {id};
        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        SysArticle ret = db.queryForBean(sql, SysArticle.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to query sys_article item for
    public SysArticle querySysArticleFlag(String flag) {
        String sql = "select * from sys_article where flag=?";

        Object[] params = {flag};
        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        SysArticle ret = db.queryForBean(sql, SysArticle.class, params);
        String code = db.getErrCode();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            this.log(db.getMsg());
        }
        this.setErrCode(code);
        return ret;
    }

    //to query SysArticle record count
    public int querySysArticle(Map<String, Object> cdt) {
        //代理商数据隔离
        cdt.put("agentId", CloudContextUtils.getAgentId());

        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select count(id) from sys_article where 1=1 ");
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            if (c.getKey().equals("content")) {
                sb.append(" and (title like ? or  content like ? )");
                list.add("%" + c.getValue() + "%");
                list.add("%" + c.getValue() + "%");
            } else {
                sb.append(" and " + c.getKey() + "=? ");
                list.add(c.getValue());
            }
        }
        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        Long ret = (Long) db.queryFieldValue(sb.toString(), Long.class, params, 1);
        this.setErrCode(db.getErrCode());
        return ret.intValue();
    }

    //to query SysArticle for record list with condition,if page or pagesize less than 0, means without page
    public List<SysArticleView> querySysArticleList(Map<String, Object> cdt, int page, int pagesize) {
        //代理商数据隔离
        if (!cdt.containsKey("sa.agentId")) {
            cdt.put("sa.agentId", CloudContextUtils.getAgentId());
        }

        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select *,");
        sb.append("(select t.description from dic_paramindex n,dic_paramitem t where t.paramId=n.paramEName  and n.paramEName='article' and t.value= sa.parentId) as typeName ");
        sb.append("from sys_article sa where 1=1");
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            if (c.getKey().equals("content")) {
                sb.append(" and (title like ? or  content like ? )");
                list.add("%" + c.getValue() + "%");
                list.add("%" + c.getValue() + "%");
            } else if (c.getKey().equals("typeId")) {
                sb.append(" and (typeId like ? )");
                list.add("" + c.getValue() + "%");
            } else {
                sb.append(" and " + c.getKey() + "=?");
                list.add(c.getValue());
            }
        }
        sb.append(" order by publishTime desc ");
        if (page > 0 && pagesize > 0) {
            sb.append(String.format(" limit %d, %d", (page - 1) * pagesize, pagesize));
        }
        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        List<SysArticleView> rets = db.queryForBeans(sb.toString(), SysArticleView.class, params);
        this.setErrCode(db.getErrCode());
        return rets;
    }

    /**
     * 获取附件的文章.
     *
     * @param id        当前文章ID.
     * @param direction 1-下一条，其他-上一条
     * @param parentId  文章分类.
     * @param typeId    文章类型.
     * @return 文章.
     */
    public SysArticleView getRecent(Integer id, Integer direction, String parentId, String typeId) {
        StringBuilder sql = new StringBuilder("select * from sys_article where publishTime ");
        sql.append(1 == direction ? "<=" : ">=").append(" (select publishTime from sys_article where id=?) ");
        sql.append(" and id!=? ");
        List<Object> params = new ArrayList<>();
        params.add(id);
        params.add(id);

        //代理商数据隔离
        sql.append(" and agentId=? ");
        params.add(CloudContextUtils.getAgentId());

        if (!StrTool.isBlankStr(parentId)) {
            sql.append(" and parentId = ? ");
            params.add(parentId);
        }
        if (!StrTool.isBlankStr(typeId)) {
            sql.append(" and typeId like ? ");
            params.add(typeId + "%");
        }
        sql.append("order by publishTime ").append(1 == direction ? "desc" : "asc").append(" limit 1");
        List<SysArticleView> views = db.queryForBeans(sql.toString(), SysArticleView.class, params.toArray());
        if (null != views && !views.isEmpty()) {
            return views.get(0);
        }
        return null;
    }

    //to query SysArticle for record list with condition,if page or pagesize less than 0, means without page
    public List<SysArticle> querySysArticleList(Map<String, Object> cdt) {
        //代理商数据隔离
        cdt.put("agentId", CloudContextUtils.getAgentId());

        List<Object> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder("select * from sys_article where 1=1");
        for (Map.Entry<String, Object> c : cdt.entrySet()) {
            if (c.getKey().equals("title")) {
                sb.append(" and title like ? ");
                list.add("%" + c.getValue() + "%");
            } else if (c.getKey().equals("content")) {
                sb.append(" and content like ? ");
                list.add("%" + c.getValue() + "%");
            } else {
                sb.append(" and " + c.getKey() + "=?");
                list.add(c.getValue());
            }
        }
        sb.append(" order by showIndex Desc");
        Object[] params = new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        List<SysArticle> rets = db.queryForBeans(sb.toString(),
                SysArticle.class, params);
        this.setErrCode(db.getErrCode());
        return rets;
    }

    //获取listId
    public int getNewshowIndex(String parentId) {
        String sql = "select max(showIndex) from sys_article where showIndex>=? and parentId=?";
        Object[] params = {1, parentId};

        //代理商数据隔离
        sql += " and agentId=? ";
        params = CObjectTool.objectArrAddValue(params, CloudContextUtils.getAgentId());

        Integer uid = (Integer) db.queryFieldValue(sql, Integer.class, params, 1);
        if (uid == null) {
            return 1;
        }

        return uid.intValue() + 1;
    }

    /**
     * 初始化代理平台文章.
     * @param agentId 代理商ID.
     * @param agentName 代理商名称.
     * @return affect line number.
     */
    public Integer initAgent(Integer agentId, String agentName) {
        String sql = "insert into sys_article (attachmentUrl, authorId, authorName, content, parentId, publishTime, " +
                "showIndex, state, title, typeId, visitors, flag, agentId) select attachmentUrl, '" + agentId + "'," +
                "'" + agentName + "', content, parentId, publishTime, showIndex, state, title, typeId, visitors, " +
                "flag, '" + agentId + "' from sys_article where agentId=0; ";
        Integer affect = this.db.executeSql(sql);
        this.setErrCode(db.getErrCode());
        return affect;
    }
}